package algorithms4g

import "fmt"

type ListNode struct {
	Val  int
	Next *ListNode
}

func init() {
	l1 := &ListNode{Val: 3}
	l2 := &ListNode{Val: 4, Next: l1}
	l3 := &ListNode{Val: 2, Next: l2}

	la := &ListNode{Val: 4}
	lb := &ListNode{Val: 6, Next: la}
	lc := &ListNode{Val: 5, Next: lb}
	res := addTwoNumbers(l3, lc)
	s := []int{}
	for res != nil {
		s = append(s, res.Val)
		res = res.Next
	}
	fmt.Println("两数相加", s)
}

/**
两数相加
*/
func addTwoNumbers(l1 *ListNode, l2 *ListNode) (head *ListNode) {
	var tail *ListNode
	carry := 0
	for l1 != nil || l2 != nil {
		val1, val2 := 0, 0
		if l1 != nil {
			val1 = l1.Val
			l1 = l1.Next
		}
		if l2 != nil {
			val2 = l2.Val
			l2 = l2.Next
		}
		sum := val1 + val2 + carry
		sum, carry = sum%10, sum/10
		if head == nil {
			head = &ListNode{Val: sum}
			tail = head
		} else {
			tail.Next = &ListNode{Val: sum}
			tail = tail.Next
		}
	}
	if carry > 0 {
		tail.Next = &ListNode{Val: carry}
	}
	return head
}
